package xx.iverson.interceptor;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import xx.iverson.enums.EnumException;
import xx.iverson.exception.BusinessException;
import xx.iverson.service.SyAuthService;

import java.util.Objects;

/**
 * xx.iverson.interceptor.AuthInterceptor
 * 描述：认证拦截器
 * on 2025/6/18-下午3:12
 *
 * @author weijx
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Resource
    private SyAuthService authService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 放行 OPTIONS 请求
        if (Objects.equals(request.getMethod(), "OPTIONS")) {
            return true;
        }

        // 从请求头获取 Token
        String token = request.getHeader("Authorization");
        if (token == null || token.isEmpty()) {
            throw new BusinessException(EnumException.USER_NOT_AUTH);
        }

        // 去掉 "Bearer " 前缀（如果有）
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }

        // 检查 Redis 中是否存在该 Token
        if (authService.verifyToken(token).getCode() != 200) {
            throw new BusinessException(EnumException.USER_NOT_LOGIN);
        }

        return true;
    }
}